// Copyright 2010 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package utils;

import com.google.api.adwords.lib.AdWordsUser;
import com.google.api.adwords.lib.ReportDate;
import com.google.api.adwords.lib.ServiceAccountantManager;
import com.google.api.adwords.lib.utils.UnitsUsageMap;
import com.google.api.adwords.lib.utils.UnitsUtils;

import java.util.Date;
import java.util.Map;

/**
 * This demo displays API method usage for this month for all methods provided
 * by the AdWords API. Running this example will consume at least 71 quota
 * units. It should be noted that this data is not in real time and is refreshed
 * every few hours.
 */
public class UnitsUtilsDemo {
  public static void main(String args[]) throws Exception {
    // Set the date range for this month. Dates are inclusive.
    Date endDate = new ReportDate().toCalendar().getTime();
    Date startDate = new ReportDate(
        new ReportDate().getYear(), new ReportDate().getMonth(), 1).toCalendar().getTime();

    // Log SOAP XML request and response.
    //AdWordsServiceLogger.log();

    // Get AdWordsUser from "~/adwords.properties".
    AdWordsUser user = new AdWordsUser();

    UnitsUtils unitsUtils = new UnitsUtils(user);

    System.out.println("Retrieving method usage...");
    Map<String, Long> methodUsage = unitsUtils.getMethodUsage(startDate, endDate);
    // Display the method usage.
    print(methodUsage);

    System.out.println("\nRetrieving units usage per client...");
    UnitsUsageMap unitsUsageMap =  unitsUtils.getClientUnitsUsage(startDate, endDate);
    // Display the units usage.
    print(unitsUsageMap.getUnitsUsageMap());
    // Display the double counted children.
    System.out.println("\nThe following emails have been double counted: ");
    for (String clientEmail : unitsUsageMap.getDoubleCountedChildren()) {
      System.out.println(clientEmail + " was double counted.");
    }

    // Determining how much quota all these operations have consumed.
    System.out.println("Total Quota unit cost for this run: "
        + ServiceAccountantManager.getInstance().getTotalUnitCount());
  }

  /**
   * Pretty prints {@code map} using the {@code toString()} method.
   */
  private static void print(Map map) {
    System.out.println(map.toString()
        .replaceAll(", ", "\n")
        .replaceAll("=", " = ")
        .replaceAll("\\{", "")
        .replaceAll("\\}", ""));
  }
}
